package com.aiju.cash.ui.account;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.aiju.app.SimpleHttpCallback;
import com.aiju.base.activity.BaseTitleActivity;
import com.aiju.bean.Account;
import com.aiju.cash.R;
import com.aiju.cash.core.api.AccountApi;
import com.aiju.cash.core.event.AccountEvent;
import com.aiju.cash.ui.account.adapter.ViewPagerAdapter;
import com.aiju.cash.ui.account.entity.ItemList;
import com.aiju.cash.ui.account.manager.AccountType;
import com.aiju.cash.ui.account.manager.AccountTypeManager;
import com.aiju.cash.util.GsonHelper;
import com.aiju.common.PixValue;
import com.aiju.common.event.EventCenter;
import com.aiju.utils.DateUtil;
import com.aiju.utils.L;
import com.aiju.utils.T;
import com.aiju.utils.Util;
import com.aiju.widgit.dialog.AccountDialog;
import com.aiju.widgit.dialog.ListDialog;
import com.aiju.widgit.layout.SettingItemTextView;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import static com.aiju.cash.ui.good.GoodAddActivity.REQUEST_CODE;

/**
 * @author: 佐为
 * @date: 2017-03-29 16:11
 * @version: V1.0
 * @Description: 创建账目，编辑账目
 */
public class AccountCreatActivity extends BaseTitleActivity implements View.OnClickListener, OnDateSetListener {

    public static List<String> msg = new ArrayList<>();

    static {
        msg.add("支付宝");
        msg.add("微信钱包");
        msg.add("现金");
        msg.add("信用卡");
        msg.add("储值卡");
        msg.add("其他");
        msg.add("不选账户");
    }

    public static final int CREATE = 0;
    public static final int EDIT = 1;

    private TextView typeView;

    private EditText moneyTextView;
    private SettingItemTextView timeTextView;
    private SettingItemTextView accountTextView;
    private SettingItemTextView accountTypeTextView;

    private SettingItemTextView remarkTextView;

    private ViewPager mViewPager;

    private List<View> viewList = new ArrayList<>();

    private ImageView imageView;

    private String money, accountId;
    //账目类型 1：收入 2：支出
    private String type = "1";
    //账户类型 0：现金 1：支付宝 2：微信
    private String accountType = "1";
    //备注  	图片类别 类目名称 创建日期
    private String remark = "", imageType = "1", categoryName = "通用", createDate = "2017-04-08 15:33:20";

    //顶部
    private TextView in, out;

    private ItemList.Item item;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account_create);
        setRightTitle("保存");

        AccountTypeManager.init();
        accountApi = new AccountApi(mDialogHelper);
        imageView = (ImageView) findViewById(R.id.iv_account_money);
        typeView = (TextView) findViewById(R.id.tv_account_money);
        moneyTextView = (EditText) findViewById(R.id.set_creat_type);
        accountTextView = (SettingItemTextView) findViewById(R.id.set_create_account);

        timeTextView = (SettingItemTextView) findViewById(R.id.set_create_time);
        accountTypeTextView = (SettingItemTextView) findViewById(R.id.set_create_type);
        remarkTextView = (SettingItemTextView) findViewById(R.id.set_create_remark);
        remarkTextView.getRightView().setPadding(PixValue.dp.valueOf(15), PixValue.dp.valueOf(12), 0, PixValue.dp.valueOf(12));
        final int showType = getIntent().getIntExtra("showType", 0);
        if (showType == EDIT) {
            item = (ItemList.Item) getIntent().getSerializableExtra("item");
            type = item.getType();
            categoryName = item.getCategoryName();
            createDate = item.getModifyDate();
            money = item.getSimpleMoney();
            accountType = String.valueOf(msg.indexOf(item.getAccountType()));
            remark = item.getRemark();

            typeView.setText(item.getCategoryName());
            imageView.setImageResource(AccountTypeManager.getPic(item.getCategoryName()));

            moneyTextView.setText(money);
            moneyTextView.setSelection(money.length());
            timeTextView.setRightText(createDate);
            accountTypeTextView.setRightText(msg.get(Integer.valueOf(accountType)));
            remarkTextView.setRightText(remark);
        } else {
            createDate = DateUtil.getCurrentDate(DateUtil.dateFormatYMDHMS);
            timeTextView.setRightText(createDate);
            boolean quick = getIntent().getBooleanExtra("quick", false);
            if (quick) {
                accountTextView.setVisibility(View.VISIBLE);
                accountTextView.setRightText("暂无");
                requsetAccountList();
            } else {
                accountTextView.setVisibility(View.GONE);
                accountId = getIntent().getStringExtra("accountId");
                type = getIntent().getStringExtra("type");
            }
        }

        mAiJuTitleBarView.setCustomizedCenterView(getCenterView());
        mAiJuTitleBarView.setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                money = moneyTextView.getText().toString();
                if (TextUtils.isEmpty(money)) {
                    T.ToastShort("请输入金额");
                    return;
                }
                if (TextUtils.isEmpty(accountType)) {
                    T.ToastShort("请选择账户类型");
                    return;
                }
                if (TextUtils.isEmpty(createDate)) {
                    T.ToastShort("请选择时间");
                    return;
                }

                Double d = Double.valueOf(money);
                if (d < 0) {
                    T.ToastShort("请输入大于0的金额");
                    return;
                }
                if (d > 100000000) {
                    T.ToastShort("金额需小于一亿，请重新输入");
                    return;
                }

                if (showType == EDIT) {
                    requsetItemUpdate(categoryName, money, accountType, createDate, remark);
                } else {
                    requsetItemSave();
                }
            }
        });
        if (type.equals("2")) {
            out.performClick();
        }


        mViewPager = (ViewPager) findViewById(R.id.vp_account);

        timeTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showTimeDialog();
            }
        });
        remarkTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(AccountCreatActivity.this, AccountRemarkActivity.class);
                if (remark != null) {
                    intent.putExtra("data", remark);
                }
                startActivityForResult(intent, REQUEST_CODE);
            }
        });
        accountTypeTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog();
            }
        });
    }

    private AccountApi accountApi;
    private LinkedList<Account> accountList = new LinkedList<>();

    /**
     * 请求账本列表
     */
    private void requsetAccountList() {
        accountApi.accountList(1, 6, new SimpleHttpCallback() {
            @Override
            protected void onDataSuccess(String data) {
                accountList.clear();
                List<Account> list = GsonHelper.convertEntities(data, Account.class);
                for (Account account : list) {
                    if (account.getIsDefault().equals("1")) {
                        accountList.addFirst(account);
                    } else {
                        accountList.add(account);
                    }
                }
                if (Util.isEmpty(AccountCreatActivity.this.accountList)) {
                    showCreatAccountDialog();
                } else {
                    accountId = AccountCreatActivity.this.accountList.get(0).getId();
                    accountTextView.setRightText(accountList.get(0).getName());
                    if (accountList.get(0).getIsDefault().equals("1")) {
                        selectItem = accountList.get(0).getName() + "<font color='#FF9900'> (默认)</font>";
                    } else {
                        selectItem = accountList.get(0).getName();
                    }
                    accountTextView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            showSelectAccountDialog();
                        }
                    });
                }
            }
        });
    }

    /**
     * 显示创建账本对话框
     */
    private void showCreatAccountDialog() {
        new AccountDialog(this)
                .setLayoutParams()
                .setOnAccount(new AccountDialog.OnAccount() {
                    @Override
                    public void onAccount(String name, int color) {
                        requsetAccountAdd(name, color);
                    }
                })
                .setCancelable(false)
                .setCanceledOnTouchOutside(false)
                .show();
    }

    /**
     * 账本添加
     */
    private void requsetAccountAdd(String name, int color) {
        accountApi.accountAdd(name, color, new SimpleHttpCallback() {
            @Override
            protected void onDataSuccess(String data) {
                requsetAccountList();
                T.ToastShort("账本添加成功");
            }

            @Override
            protected void onDataFailure(int code, String msg) {
                super.onDataFailure(code, msg);
                T.ToastShort("账本添加失败");
            }
        });
    }

    /**
     * 显示选择账本对话框
     */
    private void showSelectAccountDialog() {
        final List<String> accountName = new ArrayList<>();
        for (Account account : accountList) {
            if (account.getIsDefault().equals("1")) {
                accountName.add(account.getName() + "<font color='#FF9900'> (默认)</font>");
            } else {
                accountName.add(account.getName());
            }
        }
        new ListDialog(this)
                .setLayoutParams()
                .setSelectString(selectItem)
                .setData(accountName)
                .setOnItemOnClick(new ListDialog.OnItemOnClick() {
                    @Override
                    public void click(String item, int position) {
                        selectItem = item;
                        Account account = accountList.get(position);
                        accountTextView.setRightText(account.getName());
                        accountId = account.getId();
                    }
                }).show();
    }

    private String selectItem;

    /**
     * 账目保存
     */
    private void requsetItemSave() {
        accountApi.itemSave(categoryName, accountId, money, type, accountType,
                createDate, remark, imageType, new SimpleHttpCallback() {
                    @Override
                    protected void onDataSuccess(String data) {
                        T.ToastShort("账目已保存至"+accountTextView.getRightString()+"账本");
                        EventCenter.getInstance().post(new AccountEvent(1));
                        finish();
                    }
                });
    }

    /**
     * 账目修改
     */
    private void requsetItemUpdate(String categoryName, String money, String accountType, String modifyDate, String remark) {
        accountApi.itemUpdate(item.getId(), type, categoryName, money, accountType, modifyDate,
                remark, new SimpleHttpCallback() {
                    @Override
                    protected void onDataSuccess(String data) {
                        T.ToastShort("账目编辑成功");
                        EventCenter.getInstance().post(new AccountEvent(1));
                        finish();
                    }
                });
    }

    /**
     * 选择时间dialog
     */
    private void showTimeDialog() {
        long tenYears = 10L * 365 * 1000 * 60 * 60 * 24L;
        TimePickerDialog mDialogAll = new TimePickerDialog.Builder()
                .setCallBack(this)
                .setCancelStringId("取消")
                .setSureStringId("确定")
                .setTitleStringId("时间")
                .setYearText("年")
                .setMonthText("月")
                .setDayText("日")
                .setHourText("时")
                .setMinuteText("分")
                .setCyclic(false)
                .setMinMillseconds(System.currentTimeMillis() - tenYears)
                .setMaxMillseconds(System.currentTimeMillis() + tenYears)
                .setCurrentMillseconds(DateUtil.getDateByFormat(createDate, DateUtil.dateFormatYMDHMS).getTime())
                .setThemeColor(Color.parseColor("#f6f6f6"))
                .setType(Type.ALL)
                .setWheelItemTextNormalColor(getResources().getColor(R.color.timetimepicker_default_text_color))
                .setWheelItemTextSelectorColor(getResources().getColor(R.color.app_text_color))
                .setWheelItemTextSize(14)
                .build();
        mDialogAll.show(getSupportFragmentManager(), "all");
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
        createDate = DateUtil.getStringByFormat(millseconds, DateUtil.dateFormatYMDHMS);
        timeTextView.setRightText(createDate);
    }

    private class MyBaseAdapter extends BaseAdapter {

        private Context mContext;
        private List<AccountType> accountTypes;

        public MyBaseAdapter(Context context, List<AccountType> accountTypes) {
            this.mContext = context;
            this.accountTypes = accountTypes;
        }

        @Override
        public int getCount() {
            return accountTypes.size();
        }

        @Override
        public Object getItem(int position) {
            return accountTypes.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            AccountType type = accountTypes.get(position);

            TextView textView = new TextView(mContext);
            //textView.setBackgroundColor(Color.RED);
            textView.setGravity(Gravity.CENTER);
            textView.setTextSize(12);
            textView.setTextColor(Color.parseColor("#666666"));
            textView.setText(type.getName());

            Drawable drawable = getResources().getDrawable(type.getPic());
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            textView.setCompoundDrawables(null, drawable, null, null);
            textView.setCompoundDrawablePadding(PixValue.dp.valueOf(5));

            textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT));
            return textView;
        }
    }

    @Override
    protected void onResume() {
        L.d("onResume() ");
        mViewPager.setAdapter(null);
        setViewPagerView();
        super.onResume();
    }

    private GridView getGridView(final List<AccountType> types) {
        GridView gridView = new GridView(this);
        gridView.setPadding(PixValue.dp.valueOf(15), PixValue.dp.valueOf(14), PixValue.dp.valueOf(14), PixValue.dp.valueOf(15));
        gridView.setHorizontalSpacing(PixValue.dp.valueOf(10));
        gridView.setVerticalSpacing(PixValue.dp.valueOf(10));
        gridView.setNumColumns(5);
        //gridView.setBackgroundColor(Color.GREEN);
        gridView.setAdapter(new MyBaseAdapter(this, types));
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                AccountType type = types.get(position);
                if (type.getName().equals("添加")) {
                    startActivity(AccountTypeActivity.class);
                } else {
                    categoryName = type.getName();
                    typeView.setText(type.getName());
                    imageView.setImageResource(type.getPic());
                }
            }
        });
        return gridView;
    }

    private void setViewPagerView() {
        viewList.clear();
        List<AccountType> selectAccountType = AccountTypeManager.getSelectAccountType();
        int mo = selectAccountType.size() % 10;
        int conut = selectAccountType.size() / 10;
        if (mo != 0) {
            conut += 1;
        }
        for (int i = 0; i < conut; i++) {
            if (i == conut - 1) {
                viewList.add(getGridView(selectAccountType.subList(i * 10, selectAccountType.size())));
            } else {
                viewList.add(getGridView(selectAccountType.subList(i * 10, (i + 1) * 10)));
            }
        }
        mViewPager.setAdapter(new ViewPagerAdapter(viewList));
    }

    private void showDialog() {
        new ListDialog(this)
                .setLayoutParams()
                .setData(msg)
                .setOnItemOnClick(new ListDialog.OnItemOnClick() {
                    @Override
                    public void click(String item, int position) {
                        accountType = String.valueOf(msg.indexOf(item) + 1);
                        accountTypeTextView.setRightText(item);
                    }
                }).show();
    }


    private View getCenterView() {
        View inflate = LayoutInflater.from(this).inflate(R.layout.layout_account, null);
        in = (TextView) inflate.findViewById(R.id.tv_account_in);
        out = (TextView) inflate.findViewById(R.id.tv_account_out);
        in.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                type = "1";
                in.setTextColor(Color.parseColor("#393a3e"));
                in.setBackgroundResource(R.drawable.shape_discount_left);
                out.setBackgroundColor(getResources().getColor(R.color.transparent));
                out.setTextColor(getResources().getColor(R.color.white));
            }
        });

        out.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                type = "2";
                out.setTextColor(Color.parseColor("#393a3e"));
                out.setBackgroundResource(R.drawable.shape_discount_right);
                in.setBackgroundColor(getResources().getColor(R.color.transparent));
                in.setTextColor(getResources().getColor(R.color.white));
            }
        });

        return inflate;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE) {
            if (resultCode == 0) {
                remark = data.getStringExtra("remark");
                remarkTextView.setRightText(remark);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
